import experimental.prophet as prophet


######################################
# Feature
def kimchi_premium(products_1, sub_req_1, products_2, sub_req_2, interval):
  books_1 = []
  books_2 = []
  for p_1, p_2 in zip(products_1, products_2):
    feed_1 = prophet.fastfeed_coin(p_1, sub_req_1)
    books_1 += [prophet.get_book_from_fastfeed(feed_1)]

    feed_2 = prophet.fastfeed_coin(p_2, sub_req_2)
    books_2 += [prophet.get_book_from_fastfeed(feed_2)]

  usdkrw_rate = 1200.
  row = []
  for product_1, book_1, book_2 in zip(products_1, books_1, books_2):
    mid_p_1 = (book_1.ask0.price + book_1.bid0.price) / 2. / usdkrw_rate
    mid_p_2 = (book_2.ask0.price + book_2.bid0.price) / 2.
    row += [(mid_p_1 / mid_p_2).named_ref(str(product_1))]

  return row


def vwap(products, sub_req, interval):
  row = []

  for p in products:
    feed = prophet.fastfeed_coin(p, sub_req)
    trade = prophet.create_node('fastfeed.Trade', [feed.trade]).outputs
    tv = prophet.time_moving_window(trade.price * trade.qty, interval).sum()
    tv = prophet.cond(tv > 1e-9, tv, 0.)
    tq = prophet.time_moving_window(trade.qty, interval).sum()
    tq = prophet.cond(tq > 1e-9, tq, 0.)

    vwap = (tv / tq).named_ref(str(p))
    row.append(vwap)

  return row


######################################
# Feature instance
def kimchi_upbit_okex(interval):
  from coin.exchange.upbit_v1.kr_rest.product import UpbitProduct
  from coin.exchange.okex.kr_rest.product import OkexProduct

  products_1 = []
  products_2 = []
  for coin in ['BTC', 'ETH', 'XRP', 'BCHABC', 'LTC', 'EOS']:
    products_1.append(UpbitProduct.FromStr('%s-KRW' % coin))
    products_2.append(OkexProduct.FromStr('%s-USDT' % coin))

  return kimchi_premium(products_1, 'Spot.Upbit', products_2, 'Spot.Okex.v3', interval)


def vwap_okex(interval):
  from coin.exchange.okex.kr_rest.product import OkexProduct

  products = []
  for coin in ['BTC', 'ETH', 'XRP', 'BCHABC', 'LTC', 'EOS']:
    products.append(OkexProduct.FromStr('%s-USDT' % coin))
  return vwap(products, 'Spot.Okex.v3', interval)


FEATURE_INSTANCES = {
    'kimchi_upbit_okex': kimchi_upbit_okex,
    'vwap_okex': vwap_okex,
}
